#include <stdio.h>
#include <ctype.h>
#include <string.h>

#define KEY 6
char *keyword[KEY] = {"for", "if", "then", "else", "while", "do"};
char id[1024];
int num;
int token;

void lexical(FILE *fp) {
	char x = getc(fp);
	num=0;
	strcpy(id, "\0");
	if(x>='a'&&x<='z'||x>='A'&&x<='Z')
    {
        id[num++]=x;
        //if(x>='A'&&x<='Z'){
            do{
            x=getc(fp);
            if(x>='a'&&x<='z'||x>='A'&&x<='Z')
            {
             id[num++]=x;
            }
            else
            {
            ungetc(x,fp);
            int i;
            for(i=0;i<6;i++)
            if(!strcmp(id,keyword[i]))
               {
                   token=i+1;
                   break;
               }
            if(i==6)
                token=10;
            break;
            }
            }while(1);
            id[num]='\0';
    }
    else if(x>='0'&&x<='9')
    {
        num=x-48;
       do
       {
           x=getc(fp);
           if(x>='0'&&x<='9')
           {
            num+=num*10+x-48;
           }
           else
            {ungetc(x,fp);break;}
       }while(1);
       token=11;
    }
    else
    {
        id[num++]=x;
        switch(x){
    case '+':
        token=13;break;
    case '-':
        token=14;break;
    case '*':
        token=15;break;
    case '/':
        token=16;break;
    case ':':
        if((x=getc(fp))=='=')
            {id[num++]='=';token=18;}
        else
        {
            ungetc(x,fp);
            token=17;
        }
        break;
    case '<':
        x=getc(fp);
        if(x=='=')
            {id[num++]='=';token=22;}
            else if(x=='>')
            {
                id[num++]='>';token=21;
            }
        else
        {
            ungetc(x,fp);
            token=20;
        }
        break;
    case '>':
        x=getc(fp);
        if(x=='=')
            {id[num++]='=';token=24;}
        else
        {
            ungetc(x,fp);
            token=23;
        }
        break;
    case '=':
        token=25;break;
    case ';':
        token=26;break;
    case '(':
        token=27;break;
    case ')':
        token=28;break;
    case '#':
        token=0;break;
    default:
        if(x==EOF)
            break;lexical(fp);
        }
        id[num]='\0';

    }

	//num = 0;
	//strcpy(id, "\0");

	//process x
	//process each regex here
	//store the result in global variables id, num, or token
	//in case of backtrack, use
	//ungetc(x, fp);

}

int main(int argc, const char *argv[])
{
	if(argc < 2) {
		printf("insufficient args\n");
		return 1;
	}
    //char filename[]="C:\\Users\\Administrator\\compiler-homework2\\test1.txt";

	FILE *fp = fopen(argv[1], "r");
	//FILE *fp = fopen(filename, "r");
	do {
		lexical(fp);
		switch(token) {
			case 10: printf("(id, %s)\n", id); break;
			case 11: printf("(num, %d)\n", num); break;
			case -1: printf("error!\n"); break;
			default: printf("(%d, %s)\n", token, id);
		}
	} while(token != 0);


	fclose(fp);
	return 0;
}
